package service.impl;

import common.impl.exception.ServiceException;

import model.MClasses;
import net.sf.json.JSONObject;
import service.interf.IClasses;
import dao.interf.IClassesDao;
import dao.interf.ITeacherDao;
import dao.pojo.Classes;
import dao.pojo.Teacher;

public class ClassesImpl implements IClasses{
	private IClassesDao classesDao;
	private ITeacherDao teacherDao;
	
	public void setClassesDao(IClassesDao classesDao) {
		this.classesDao = classesDao;
	}
	
	public void setTeacherDao(ITeacherDao teacherDao) {
		this.teacherDao = teacherDao;
	}

	@Override
	public String add(MClasses model) {
		Classes classes = new Classes();
		classes.setClassName(model.getClassName());
		Teacher tea = teacherDao.getById(model.getTeaId());
		if (tea == null) {
			throw new ServiceException("ERR-0021");
		} else {
			classes.setTeacher(tea);
		}
		return classesDao.add(classes);
	}
	
	@Override
	public String getById(MClasses model) {
		Classes classes = classesDao.getById(model.getClassId());
		if(null == classes) {
			throw new ServiceException("ERR-0031");
		}
		JSONObject obj = new JSONObject();
		obj.put("classesId", classes.getClassId());
		if(null != classes.getTeacher())
			obj.put("teaId", classes.getTeacher().getTeaId());
		obj.put("classesName", classes.getClassName());
		return obj.toString();
	}

	@Override
	public String deleteById(Integer id) {
		classesDao.deleteById(id);
		return "1";
	}

	@Override
	public String edit(MClasses model) {
		Classes classes = classesDao.getById(model.getClassId());
		if (null == classes) {
			throw new ServiceException("ERR-0031");
		}
		Teacher tea = teacherDao.getById(model.getTeaId());
		if (tea == null) {
			throw new ServiceException("ERR-0021");
		} else {
			classes.setTeacher(tea);
		}
		classes.setClassName(model.getClassName());
		
		classesDao.edit(classes);
		return "1";
	}


}
